//
//  BaseViewController.swift
//  StudyDY
//
//  Created by yinchangming on 2018/6/29.
//  Copyright © 2018年 yinchangming. All rights reserved.
//

import UIKit
import AVFoundation
class BaseViewController: UIViewController {
    var contentView:UIView?
    lazy var loadingView:UIImageView={ () -> UIImageView in
        let imageView=UIImageView(image: UIImage(named: "img_loading_1"))
        imageView.animationImages=[UIImage(named: "img_loading_1")!,UIImage(named: "img_loading_2")!]
        imageView.center=self.view.center
        imageView.animationDuration=0.5
        imageView.animationRepeatCount=LONG_MAX
        imageView.autoresizingMask=[.flexibleTopMargin,.flexibleBottomMargin]
        return imageView
    }()
    lazy var videoqueue=DispatchQueue.global()
    
    lazy var  session=AVCaptureSession()
    lazy var  layer =   AVCaptureVideoPreviewLayer(session: session)
    override func viewDidLoad() {
        super.viewDidLoad()
        contentView?.isHidden=true
        view.backgroundColor=UIColor.white
        view.addSubview(loadingView)
        loadingView.startAnimating()
         initCamer()
    }
    func finshRequst(){
        loadingView.stopAnimating()
        loadingView.isHidden=true
        contentView?.isHidden=false
    }
    override func viewWillDisappear(_ animated: Bool) {
        session.stopRunning()
        layer.removeFromSuperlayer()
    }
}
//视频相关
extension BaseViewController{
    func initCamer(){
        finshRequst()
        //1 创建捕捉会话
        
        //2给会话设置输入（摄像头）输出
        //2.1获取摄像头
       
    
        guard let inputDevice =  AVCaptureDevice.devices().filter({ $0.position == .front }).first else {
            print("摄像头无法使用")
            return
        }
        guard let input =  try? AVCaptureDeviceInput(device: inputDevice) else {return}
        session.addInput(input)
        // 给会话设置输出
        let out =  AVCaptureVideoDataOutput()
        out.setSampleBufferDelegate(self , queue: videoqueue)
        session.addOutput(out)
        
        layer.frame=view.bounds
        view.layer.insertSublayer(layer, at: 0)
        // 开始采集
        session.startRunning()
    }
}

extension BaseViewController :AVCaptureVideoDataOutputSampleBufferDelegate{
    func captureOutput(_ output: AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        print("采集到数据")
    }
}
